/**
 * Created by linyi on 2019/3/11
 */
import React from 'react'
import PropTypes from 'prop-types'
import md5 from 'md5'
import Notification from 'rc-notification'
import { withRouter } from 'react-router'
import { request } from 'Utils'
import { userCenter as UserCenterApi } from 'ApiMapper'
import { SignIn, ValidatePhone, ResetPassword } from '../components'

const {
  SIGN_IN,
  RESET_PWD_SMS_CODE,
  CHECK_SMS_CODE,
  RESET_PASSWORD
} = UserCenterApi

class SceneWrapper extends React.Component {
  constructor(props) {
    super(props)
    this.resetPWDRef = React.createRef()

    console.log(this.props)

    this.state = {
      currentScene: 'sign-in', // 当前场景，sign-in / validate-phone / reset-password
      loading: false,
      errMsg: '',
      fetchCodeTimer: 60,
      fetchingCode: false,
      validated: {} // 已验证的手机+验证码
    }
  }

  onForgetPWDClick = () => {
    this.nextScene('validate-phone')
  }

  onReturnSignInClk = () => {
    this.nextScene('sign-in')
  }

  onSignInSubmit = ({ username, password }) => {
    this.setState({ loading: true })
    request(SIGN_IN, 'POST', {
      data: {
        username,
        password: md5(password),
        osType: '',
        deviceToken: ''
      },
      params: { businessType: '41' },
      loading: false
    })
      .then(data => {
        const { result: accountInfo } = data
        localStorage.setItem('account', JSON.stringify(accountInfo))
        const {
          history
          // location: { search },
        } = this.props
        // console.log(search)
        // todo: get next and redirect to it
        history.push('/orders')
      })
      .catch(e => this.setState({ errMsg: e, loading: false }))
  }

  onFetchCodeClk = phone => {
    if (!/^1[34578]\d{9}$/.test(phone.trim())) {
      this.setState({ errMsg: '非法的手机号' })
      return
    }
    this.setState({ fetchingCode: true })
    request(RESET_PWD_SMS_CODE, 'POST', { data: { telephone: phone } })
      .then(() => {
        this.setState({ fetchCodeTimer: 59 })
        const itv = setInterval(
          // start sms code sent timer
          () =>
            this.setState(({ fetchCodeTimer }) => {
              if (fetchCodeTimer < 1) {
                clearInterval(itv)
                return { fetchCodeTimer: 60 }
              }
              return { fetchCodeTimer: fetchCodeTimer - 1 }
            }),
          1000
        )
      })
      .catch(err => this.setState({ errMsg: err }))
      .finally(() => this.setState({ fetchingCode: false }))
  }

  onValidatePhoneSubmit = data => {
    this.setState({ loading: true })
    request(CHECK_SMS_CODE, 'GET', { params: data })
      .then(() => {
        this.nextScene('reset-password')
        this.setState({ validated: data })
      })
      .catch(errMsg => this.setState({ errMsg }))
      .finally(() => this.setState({ loading: false }))
  }

  onResetPWDSubmit = data => {
    const {
      validated: { mobile: telephone, smsCode }
    } = this.state
    this.setState({ loading: true })
    const { password } = data
    request(RESET_PASSWORD, 'POST', {
      data: { password: md5(password), telephone, smsCode }
    })
      .then(() => {
        Notification.newInstance(
          {
            prefixCls: 'toast',
            style: {
              position: 'absolute',
              top: 0,
              right: 0,
              bottom: 0,
              left: 0
            },
            getContainer: () => document.querySelector('.form-box')
          },
          inst => {
            inst.notice({
              content: '重置成功',
              duration: 2,
              style: {
                position: 'absolute',
                padding: '14px 33px',
                background: 'rgba(0,0,0,0.6)',
                borderRadius: '5px',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                fontSize: '14px',
                lineHeight: 1,
                color: '#FFF'
              },
              onClose: () => {
                inst.destroy()
                this.nextScene('sign-in')
              }
            })
          }
        )
      })
      .catch(err => this.setState({ errMsg: err }))
      .finally(() => this.setState({ loading: false }))
  }

  nextScene(sceneName) {
    this.setState({ loading: false, errMsg: '', currentScene: sceneName })
  }

  render() {
    const {
      currentScene,
      loading,
      errMsg,
      fetchCodeTimer,
      fetchingCode
    } = this.state

    const scene = {
      'sign-in': (
        <SignIn
          loading={loading}
          errMsg={errMsg}
          onSubmit={this.onSignInSubmit}
          onForgetPWDClick={this.onForgetPWDClick}
        />
      ),
      'validate-phone': (
        <ValidatePhone
          ref={this.resetPWDRef}
          loading={loading}
          errMsg={errMsg}
          fetchCodeTimer={fetchCodeTimer}
          fetchingCode={fetchingCode}
          onSubmit={this.onValidatePhoneSubmit}
          onReturnClick={this.onReturnSignInClk}
          onFetchCodeClick={this.onFetchCodeClk}
        />
      ),
      'reset-password': (
        <ResetPassword
          loading={loading}
          errMsg={errMsg}
          onSubmit={this.onResetPWDSubmit}
          onReturnClick={this.onReturnSignInClk}
        />
      )
    }[currentScene]

    return scene
  }
}

SceneWrapper.propTypes = {
  history: PropTypes.objectOf(PropTypes.any).isRequired,
  location: PropTypes.objectOf(PropTypes.any).isRequired
}

export default withRouter(SceneWrapper)
